package com.jade.shoesmallinterface.service.impl;

import com.jade.shoesmallinterface.entity.Product;
import com.jade.shoesmallinterface.entity.ProductImage;
import com.jade.shoesmallinterface.mapper.ProductColorMapper;
import com.jade.shoesmallinterface.mapper.ProductMapper;
import com.jade.shoesmallinterface.mapper.ProductSizeMapper;
import com.jade.shoesmallinterface.mapper.productImageMapper;
import com.jade.shoesmallinterface.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductColorMapper productColorMapper;
    @Autowired
    private ProductSizeMapper productSizeMapper;
    @Autowired
    private productImageMapper productImageMapper;

    @Override
    public List<Product> selectAllProducts() {
        List<Product> products = productMapper.selectAllProducts();
        return processProducts(products);
    }

    @Override
    public Product selectProductById(Integer productId) {
        Product product = productMapper.selectProductById(productId);
        if (product != null) {
            return processSingleProduct(product);
        }
        return null;
    }


    @Override
    public List<Product> selectProductsByBrandOrName(String brand, String productName) {
        List<Product> products = productMapper.selectProductsByBrandOrName(brand, productName);
        return processProducts(products);
    }

    private List<Product> processProducts(List<Product> products) {
        for (Product product : products) {
            processSingleProduct(product);
        }
        return products;
    }

    private Product processSingleProduct(Product product) {
        // 获取商品颜色
        List<String> colors = productColorMapper.selectColorsByProductId(product.getProductId());
        product.setColor(colors);

        // 获取商品大小
        List<String> sizes = productSizeMapper.selectSizesByProductId(product.getProductId());
        product.setSize(sizes);

        // 获取商品图片
        List<ProductImage> images = productImageMapper.selectImageByProductId(product.getProductId());
        List<String> imageUrls = new ArrayList<>();
        for (ProductImage image : images) {
            imageUrls.add(image.getImage());
        }
        product.setProductImages(imageUrls);

        // 设置image字段为第一张图片的URL，如果有图片的话
        if (!imageUrls.isEmpty()) {
            product.setImage(imageUrls.get(0));
        }

        return product;
    }
}